// packageActivity/pages/posters-work/posters-work.js
import user from '../../../utils/user.js'
import {
    base64ToWxfile,
    wxfileTobase64,
    wait,
    toast
} from '../../../utils/util.js'
import { 
    generateQrCode,
    preciseExtension
} from "../../api/activity.js"
import {
    createClientQrCode,
    getUserAvatar,
    getEnterpriseList
} from '../../../api/app.js'
import Canvas from '../../../utils/canvas'
Page({

    data: {
        selectTypeList: [{
            text: '全选',
            callback: 'selectAll'
        }
        ],
        posterList:[],
        qrcode:'',
        isPoster:false,
        currentIndex:0,
        wholePopup:false,
        isAlonePopup:false,
        avatarUrl:'',
        userName:'',
        enterprise:{
            name:'',
            code:'',
            phone:'',
            userName:'',
            id:'',
            qrId:'',
            area:''
        },
        tipList:"",
        isSendOutBtn:false,
        qrId:'', //二维码id
    },
    async onLoad(options) {
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        })
       await this.setData({
            avatarUrl:user.avatarUrl,
            userName:user.userName
        })
        user.waitLogin().then(async()=>{
            await this.createInviteQrCode()
        })
        
    },
    onReady () {
        
    },
    onShow: function () {

    },
    onNameInput(event){
        const { value } = event.detail
        this.setData({
            ['enterprise.userName']:value
        })
    },
    onPhoneInput(event){
        const { value } = event.detail
        this.setData({
            ['enterprise.phone']:value
        })
    },
    onEnterpriseInput(event){
        const { value } = event.detail
        getEnterpriseList({
            name:value
        }).then(res=>{
            this.setData({
                tipList:res
            })
        })
    },
    onTapEnter(event){
        console.log(event,'event')
        const { name,code,area } = event.currentTarget.dataset
        this.setData({
            ['enterprise.name']:name,
            ['enterprise.code']:code,
            ['enterprise.area']:area,
            tipList:[],
            isSendOutBtn:true
        })
        console.log(this.data.isSendOutBtn,'isSendOutBtn')
    },
    isSendOut(){
        if(this.data.enterprise.userName&&this.data.enterprise.phone&&this.data.enterprise.code){
            this.setData({
                isSendOutBtn:true
            })
            console.log(this.data.isSendOutBtn)
        }
    },
    onPreciseExtension(){
        if(!this.data.enterprise.userName){
            toast('请填写姓名')
            return
        }
        if(!this.data.enterprise.phone){
            toast('请填写手机号')
            return
        }
        if(!this.data.enterprise.code){
            toast('请选择公司或检查公司是否存在')
            return
        }
        preciseExtension({
            contactName:this.data.enterprise.userName,
            contactPhone:this.data.enterprise.phone,
            customName:this.data.enterprise.name,
            creditCode:this.data.enterprise.code,
            area:this.data.enterprise.area
        }).then(res=>{
            this.setData({
                ['enterprise.id']:res.id
            })
            wx.navigateTo({
              url: '/packageActivity/pages/success/success',
              success:(res)=>{
                res.eventChannel.emit('acceptDataFromOpenerPage', { data: this.data.enterprise,type:'alone' })
                this.cancel()
              }
            })
        })
    },
    onSwiperChange(event){
        console.log(event.detail.current,'event')
        this.setData({
            currentIndex:event.detail.current
        })
    },
    onAloneSendout(){
        this.setData({
            isAlonePopup:true
        })
    },
    cancel(){
        this.setData({
            isAlonePopup:false
        })
    },
    onWholeDisplay(){
        this.setData({
            wholePopup:true
        })
    },
    onWholeHide(){
        this.setData({
            wholePopup:false
        })
    },
    createInviteQrCode() {
        // let scene = 'PPID=59666&UID=1658'
        // if (this.data.isBook) {
        //     scene = 'PCID=' + user.companyId + '&UID=' + user.userId
        // } else {
        //     scene = 'PPID=' + this.data.supplierId + '&UID=' + user.userId
        // }
        generateQrCode({
            page: 'packageActivity/pages/spread/spread',
            width: 100
        }).then(res => {
            this.setData({
                ['enterprise.qrId']:res.qrId,
                qrId:res.qrId
            })
            let qrCode = JSON.parse(res.qrbody).data // 后台返回的base64图片流
            base64ToWxfile(qrCode, Math.ceil(Math.random() * 10000000000) + '.png').then(path => {
                this.setData({
                    qrcode: path
                },()=>{
                    console.log(this.data.qrcode,'qrcode')
                })
                this.saveQrCode()
            })
        })
    },
    async saveQrCode() {
        let bg= [
            '/packageActivity/assets/img/poster/poster-bg1.png',
            '/packageActivity/assets/img/poster/poster-bg2.png',
            '/packageActivity/assets/img/poster/poster-bg3.png'
        ]
        console.log(user.userId,'userid')
        const result = await  getUserAvatar({userId: user.userId})
        const path = await base64ToWxfile(result, 'avatar.png')
        this.setData({
            avatarUrl:path
        },()=>{
            console.log(this.data.avatarUrl,'avatarUrl')
        })    
        
        // this.setData({
        //     avatarUrl:(base64 === 'undefind' || !base64) ? '/assets/img/avatar.png' : res
        // }) = (base64 === 'undefind' || !base64) ?
                
        
        for(const index in bg){
                 
        wx.showLoading({
            mask: true,
            title: '正在渲染中...'
        })
        const ctx = wx.createCanvasContext('myCanvas')
        const canvas = new Canvas(ctx)
        canvas.roundRectColor(0,0,320,500,16,'#ffffff')
        // 背景图
        canvas.roundRectColor(20,20,280,320,16,'#ffffff')
        ctx.fillStyle = "#fff"
        canvas.drawHeightCutImage(20,20,280,320,320,bg[index])
        await wait(300)
        // 头像
        canvas.drawRoundImage(index == 1 ? 36 : 32,308,60,path,'#ffffff')
        // 姓名
        canvas.fillText(user.userName,32,400,'#202536',21,'left','true')
        
        // 欢迎语
        canvas.fillText('Hi～我在子弹发薪',32,445,'#202536',12,'left')
        canvas.fillText('最好用的劳务派遣线上管理平台',32,465,'#202536',12,'left')
        // 二维码边框 qrcode
        canvas.roundRectColor(210,350,90,90,16,'#E8E9EA')
        canvas.drawHeightCutImage(212,352,86,86,86,this.data.qrcode)
        await wait(300)
        // 提示信息
        canvas.fillText('长按识别立即体验',212,465,'#9497B1',10,'left')
        
        ctx.draw(true)
        ctx.restore()
        await wait(300)
            await wx.canvasToTempFilePath({
                x: 0,
                y: 0,
                width: 320,
                height: 700,
                canvasId: 'myCanvas',
                success: async(res)=> {
                    console.log(res.tempFilePath,'转换成功',bg[index])
                    await wxfileTobase64(res.tempFilePath,true).then(async url=>{
                        // console.log(url,'url')
                        let arr = []
                        arr = this.data.posterList
                        arr.push({
                            path:res.tempFilePath,
                            src:url
                        })
                        console.log(arr,'arrarrarr',arr.length)
                        if(arr.length ===3 ){
                            wx.hideLoading()
                        }
                        // console.log(res,'res')
                        await this.setData({
                            posterList:arr,
                        },()=>{
                            // console.log(this.data.posterList,'posterList')
                        })
                    })
                }
            })
        
        }
    },
    // 图片保存
    savecanvas(success,fail){
        wx.saveImageToPhotosAlbum({
            filePath:this.data.posterList[this.data.currentIndex].path,
            success:(res)=>{
                toast(success)
                this.setData({
                    wholePopup:false
                })
            },
            fail:(rej)=>{
                toast(fail)
            }
        })
    },
    preservation(){
        this.savecanvas('保存成功','保存失败')
    },
    onToBrother(){
        this.savecanvas('保存成功，请自行发送到朋友圈','保存失败')
    },
    onShareAppMessage() {
        // scene path: '/pages/index/index?scene=' + encodeURIComponent('uId=' + user.userId + '&cId=' + user.companyId),
        return { 
            title: '「' + user.userName + '」' + ' 邀请您使用子弹发薪',
            path: '/packageActivity/pages/spread/spread?scene=' + encodeURIComponent('QRID=' + this.data.qrId ),
            imageUrl: '/packageActivity/assets/img/poster/invitation.png'
        }
    }

})